#!/usr/bin/env tsx

import { readFileSync, writeFileSync, existsSync, readdirSync } from 'fs';
import { join, extname, basename } from 'path';

const NODE_UI_DIR = '../nodes/dist/ui';
const OUTPUT_FILE = './lib/generated/ui-bundles.ts';

function generateUIBundlesModule() {
  console.log('🔨 Generating UI bundles module...');

  // Check if source directory exists
  if (!existsSync(NODE_UI_DIR)) {
    console.error(`❌ Source directory not found: ${NODE_UI_DIR}`);
    console.error('Make sure to build the nodes package first: pnpm build');
    process.exit(1);
  }

  // Get all JS files from the UI directory
  const files = readdirSync(NODE_UI_DIR);
  const jsFiles = files.filter(file => extname(file) === '.js' && !file.includes('.LICENSE'));

  if (jsFiles.length === 0) {
    console.warn('⚠️  No UI bundle files found in', NODE_UI_DIR);
    return;
  }

  // Generate the TypeScript module
  let moduleContent = `// This file is auto-generated by generate-ui-bundles-module.ts
// DO NOT EDIT MANUALLY

export const uiBundles: Record<string, string> = {
`;

  for (const file of jsFiles) {
    const nodeId = basename(file, '.js');
    const filePath = join(NODE_UI_DIR, file);
    
    try {
      const content = readFileSync(filePath, 'utf-8');
      // Escape the content for TypeScript string literal
      const escapedContent = content
        .replace(/\\/g, '\\\\')
        .replace(/`/g, '\\`')
        .replace(/\${/g, '\\${');
      
      moduleContent += `  "${nodeId}": \`${escapedContent}\`,\n`;
      console.log(`✅ Bundled ${nodeId}`);
    } catch (error) {
      console.error(`❌ Failed to read ${file}:`, error);
    }
  }

  moduleContent += `};

export function getUIBundle(nodeId: string): string | undefined {
  return uiBundles[nodeId];
}

export function hasUIBundle(nodeId: string): boolean {
  return nodeId in uiBundles;
}

export const bundledNodeIds = Object.keys(uiBundles);
`;

  // Write the module
  writeFileSync(OUTPUT_FILE, moduleContent);
  console.log(`🎉 Generated UI bundles module with ${jsFiles.length} bundles`);
  console.log(`📝 Output: ${OUTPUT_FILE}`);
}

// Run the script
if (require.main === module) {
  generateUIBundlesModule();
}

export { generateUIBundlesModule };